package vinnichenko.lab3;

/**Own packages*/
import vinnichenko.lab3.database.*;
import vinnichenko.lab3.exception.*;

/**Java core packages*/
import java.io.*;
import java.sql.*;
import java.util.*;

/**Java extension packages*/
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.naming.*;
import javax.sql.*;

/**Other packages*/
import org.w3c.dom.*;
import org.xml.sax.*;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**Servlet to allow delete existing users from database.
 * @author Igor Vinnichenko
 * @version 1.0
 */
public class DeletePersonServlet extends HttpServlet {
    /**UID*/
    private static final long serialVersionUID = 7L;

    /**Declaration and creation logger.*/
    static Logger logger = Logger.getLogger(DeletePersonServlet.class);

    /**Database object*/
    private EmployeeDB employeeDB;

    /**Servlet initialization method.*/
    public void init()throws ServletException{
        /**Get DAO attribute from servlet context.*/
        EmployeesDAO empDAO = (EmployeesDAO)getServletContext().getAttribute("eDB");

        /**If DAO doesn't exist then throw exception.*/
        if( empDAO == null ){
            throw new UnavailableException("Couldn't get database.");
        }

        /**Create database object and give it to database*/
        employeeDB = new EmployeeDB();
        employeeDB.setDatabase( empDAO );
        logger.info("DeletePersonServlet initialization successful.");
    }

    /**Method called when servlet is near to be destroyed*/
    public void destroy(){
        /**Set database object to null.*/
        employeeDB = null;
        logger.info("DeletePersonServlet destroyed.");
    }

    /**Method to process 'get' request.
     * Get request deletes from database information about employee with
     * some number.
     * @param request - servlet request.
     * @param response - servlet response.
     * @throws ServletException, IOException.
     */
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException {

        logger.debug("DeletePersonServlet, method 'Get' was called.");

        /**Set content type - text/html*/
        response.setContentType( "text/html" );
        /**Getting writer for output data*/
        PrintWriter out = response.getWriter();  
      
        try{
            /**Get employee's number.*/
            String empno = request.getParameter( "empno" );
            
            /**Delete person information from database.*/
            boolean success = employeeDB.deleteEmployee( empno );

            /** Get a DocumentBuilderFactory for creating
             * a DocumentBuilder (i.e., an XML parser)*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            /**Get a DocumentBuilder for building the DOM tree*/
            DocumentBuilder builder = factory.newDocumentBuilder();

            /**Create a new Document (empty DOM tree)*/
            Document messageDocument = builder.newDocument();
            /**Create structure of document and attribute 'value' of 'success' branch
             * with number of updated records will indicate result of execution.*/
            Element employee = messageDocument.createElement( "employee" );
            Element temp = messageDocument.createElement( "success" );
            temp.setAttribute("value", String.valueOf( success ) );
            employee.appendChild( temp );
            messageDocument.appendChild( employee );

            /**Open InputStream for XSL document*/
            InputStream xslStream = getServletContext().getResourceAsStream( "/deleteemployee.xsl" );

            /**Transform XML document using XSLT*/
            XMLTransformer.transform( messageDocument, xslStream, out );
        }catch ( ParserConfigurationException pcException ) { 
            /**catch XML parser exceptions*/
            logger.error(StackWriter.getFullStackTrace( pcException ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)pcException );
            throw new ServletException( pcException );
        }catch ( DatabaseConnectException e ){
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }catch ( EmployeeNotFoundException e ) { 
            /**catch SQL exceptions*/
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }catch ( XSLTTransformingException e ) { 
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }

        /**flush and close output stream*/
        out.flush();
        out.close();
    }   
}
